package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.framework.exception.ServiceException;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.*;
import com.mars.module.system.entity.SysUserRole;
import com.mars.module.system.mapper.SysUserRoleMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysProductRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysProductService;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品业务层处理
 *
 * @author mars
 * @date 2024-01-24
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysProductServiceImpl implements ISysProductService {

    private final SysProductMapper baseMapper;

    private final SysProductClassMapper classMapper;
    private final SysDictDataMapper dictDataMapper;
    private final SysUserRoleMapper userRoleMapper;


    private static String classId = "";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysProduct add(SysProductRequest request) {
        List<SysDictData> dataList = dictDataMapper.selectList(new QueryWrapper<>());
        List<String> words = dataList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        for (String key : words) {
            if (request.getName().contains(key)) {
                throw new ServiceException("商品名称存在敏感字【" + key + "】！请修改后上传！");
            }
        }
        SysProduct entity = new SysProduct();
        entity.setId(request.getId());
        String[] split = request.getClassId().split(",");
        entity.setClassId(split[split.length - 1]);
        entity.setName(request.getName());
        entity.setStatus(request.getStatus());
        entity.setPicture(request.getPicture());
        entity.setPrice(request.getPrice());
        entity.setStatus("0");
        entity.setSpec(request.getSpec());
        entity.setIntroduce(request.getIntroduce());
        entity.setSellPrice(request.getSellPrice());
        entity.setDeleted("0");
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysProductRequest request) {
        SysProduct entity = new SysProduct();
        entity.setId(request.getId());
        if (request.getClassId() != null) {
            String[] split = request.getClassId().split(",");
            entity.setClassId(split[split.length - 1]);
        }
        entity.setName(request.getName());
        entity.setStatus(request.getStatus());
        entity.setPicture(request.getPicture());
        entity.setPrice(request.getPrice());
        entity.setSpec(request.getSpec());
        entity.setIntroduce(request.getIntroduce());
        entity.setSellPrice(request.getSellPrice());
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysProduct getById(Long id) {
        SysProduct product = baseMapper.selectById(id);
        String classId = getClassId(Long.valueOf(product.getClassId()));
        if (StringUtils.isBlank(classId)) {
            classId = product.getClassId().toString();
        }
        product.setClassId(classId);
        return product;
    }

    public String getClassId(Long id) {
        SysProductClass productClass = classMapper.selectById(id);
        if (productClass.getParentId() != 0L) {
            classId = productClass.getParentId().toString() + "," + productClass.getId();
            getClassId(productClass.getParentId());
        }
        return classId;
    }

    @Override
    public PageInfo<SysProduct> pageList(SysProductRequest request) {
        Page<SysProduct> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysProduct> query = this.buildWrapper(request);
        IPage<SysProduct> pageRecord = baseMapper.selectPage(page, query);
        List<SysProduct> records = pageRecord.getRecords();
        List<SysProduct> recordsNew = new ArrayList<>();
        Long userId = ContextUserInfoThreadHolder.get().getId();
        for (SysProduct e : records) {
            SysProductClass productClass = classMapper.selectById(e.getClassId());
            e.setClassName(productClass == null ? "" : productClass.getClassName());
            e.setStatus(getStatusName(e.getStatus(), "product_status"));
            Long l = userRoleMapper.selectCount(new QueryWrapper<SysUserRole>().eq("user_id", userId).eq("role_id", "1052613170658541568"));
            if (l > 0) {
                e.setIsAdmin("1");
            }
            recordsNew.add(e);
        }
        if (StringUtils.isNotBlank(request.getName())) {
            recordsNew = recordsNew.stream().filter(e -> e.getName().contains(request.getName())).collect(Collectors.toList());
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }

    private String getStatusName(String value, String type) {
        List<SysDictData> reviewStatus = dictDataMapper.selectList(Wrappers.lambdaQuery(SysDictData.class)
                .eq(SysDictData::getDictType, type).orderByAsc(SysDictData::getDictSort));
        SysDictData sysDictData = reviewStatus.stream().filter(e -> value.equals(e.getDictValue())).findFirst().orElse(null);
        return sysDictData == null ? "" : sysDictData.getDictLabel();
    }

    @Override
    public List<SysProduct> list(SysProductRequest request) {
        LambdaQueryWrapper<SysProduct> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysProduct> buildWrapper(SysProductRequest param) {
        LambdaQueryWrapper<SysProduct> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getName())) {
            query.like(SysProduct::getName, param.getName());
        }
        if (param.getClassId() != null) {
            query.like(SysProduct::getClassId, param.getClassId());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.like(SysProduct::getStatus, param.getStatus());
        }
        return query;
    }

}
